package com.github.phoenics.teacher.itheima.im.user.status.servic.impl;

import com.github.phoenics.teacher.itheima.im.user.status.servic.UserStatusService;
import com.google.inject.Inject;
import com.google.inject.assistedinject.Assisted;
import lombok.extern.slf4j.Slf4j;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

import java.util.Properties;

/**
 * @author Phoenics Chow
 * on 2020年03月06日
 */
@Slf4j
public class RedisUserStatusServiceImpl implements UserStatusService {

    private static final String USER_CONN_STATUS_KEY = "IM:USER_CONN_STATUS:USERID:";

    private JedisPool jedisPool;

    @Inject
    public RedisUserStatusServiceImpl(@Assisted Properties properties) {
        JedisPoolConfig config = new JedisPoolConfig();
        config.setMaxWaitMillis(2 * 1000);
        String password = properties.getProperty("password");
        jedisPool = new JedisPool(config, properties.getProperty("host"), (Integer) properties.get("port"),
                2 * 1000, password != null && !password.isEmpty() ? password : null);
    }

    @Override
    public String online(String userId, String connectorId) {
        log.debug("[user status] user online: userId: {}, connectorId: {}", userId, connectorId);

        try (Jedis jedis = jedisPool.getResource()) {
            String oldConnectorId = jedis.hget(USER_CONN_STATUS_KEY, String.valueOf(userId));
            jedis.hset(USER_CONN_STATUS_KEY, String.valueOf(userId), connectorId);
            return oldConnectorId;
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return null;
        }
    }

    @Override
    public void offline(String userId) {
        log.debug("[user status] user offline: userId: {}", userId);

        try (Jedis jedis = jedisPool.getResource()) {
            jedis.hdel(USER_CONN_STATUS_KEY, String.valueOf(userId));
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }

    @Override
    public String getConnectorId(String userId) {
        try (Jedis jedis = jedisPool.getResource()) {
            return jedis.hget(USER_CONN_STATUS_KEY, userId);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return null;
        }
    }
}